package com.woniu.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class WechatAuthService {
    // JSON解析器
    private final ObjectMapper objectMapper = new ObjectMapper();

    // OkHttp客户端
    private final OkHttpClient client;



    // 小程序配置
//    private final String appId;
//    private final String appSecret;


    /**
     * 构造函数，传入小程序配置
     */
    public WechatAuthService(String appId, String appSecret) {
//        this.appId = appId;
//        this.appSecret = appSecret;

        // 配置OkHttp客户端，设置超时时间
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    /**
     * 通过微信临时登录凭证获取用户登录信息
     *
     * @param code 小程序登录时获取的临时凭证
     * @return 包含登录信息的Map，失败时返回null
     */
    public Map<String, Object> getLoginInfo(String code,  String appId, String appSecret) {
        // 构建请求URL
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                appId, appSecret, code
        );


        // 创建请求
        Request request = new Request.Builder()
                .url(url)
                .build();

        try {
            // 执行请求并处理响应
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    System.err.println("HTTP请求失败: " + response);
                    return null;
                }

                // 获取响应内容
                String responseBody = response.body().string();

                // 解析JSON响应
                Map<String, Object> result = objectMapper.readValue(responseBody, HashMap.class);

                // 检查微信接口返回的错误码
                if (result.containsKey("errcode") && !result.get("errcode").equals(0)) {
                    String errmsg = (String) result.get("errmsg");
                    System.err.println("微信接口返回错误: " + errmsg);
                    return null;
                }

                return result;
            }
        } catch (IOException e) {
            System.err.println("获取登录信息失败: " + e.getMessage());
            e.printStackTrace();
            return null;
        }
    }

}
